package cn.liumouren.jzxd.controller;

import cn.hutool.json.JSONUtil;
import cn.liumouren.jzxd.common.utils.PageUtils;
import cn.liumouren.jzxd.common.utils.R;
import cn.liumouren.jzxd.entity.User;
import cn.liumouren.jzxd.service.UserService;
import cn.liumouren.jzxd.utils.QueryUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Map;


/**
 * @author Freeman Liu
 * @email llw599502537@gmail.com
 * @date 2020-10-31 00:44:45
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    public static final String APPID = "wx3c9bdb6816762a08";
    public static final String SECRET = "dca6bad8e359c2e9587e5d13084e88c9";

    @ApiOperation("万能查询")
    @RequestMapping(value = "/customQuery", method = RequestMethod.GET)
    public R getSceneNames(@RequestParam Map<String, Object> map) {
        PageUtils result = QueryUtil.getResult(userService, map);
        return R.ok("查询成功", result);
    }

    /**
     * 列表
     */
    @ApiOperation("分页查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = userService.queryPage(params);

        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @ApiOperation("根据id查询")
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    public R info(@PathVariable("id") String id) {
        User user = userService.getById(id);

        return R.ok().put("data", user);
    }

    /**
     * 保存
     */
    @ApiOperation("新增")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public R save(@RequestBody User user) {
        userService.save(user);

        return R.ok();
    }

    /**
     * 修改
     */
    @ApiOperation("修改")
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public R update(@RequestBody User user) {
        userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @ApiOperation("批量删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public R delete(@RequestBody String[] ids) {
        userService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @ApiOperation("微信登录")
    @RequestMapping(value = "/wxLogin", method = RequestMethod.POST)
    public R delete(@RequestBody Map<String,String> map) {
        String code = map.get("code");
        String nickname = map.get("nickname");
        String avatar = map.get("avatar");

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID +
                "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";

        String jsonResult = restTemplate.getForObject(url, String.class); //"{\"session_key\":\"wWS8jZ0oYuj\\/noDzo5w7Gg==\",\"openid\":\"os4JL5I_Ezmnt4gVX_bUKROTCGw0\"}"
        System.out.println(jsonResult);
        if (StringUtils.isEmpty(jsonResult) || StringUtils.contains(jsonResult, "errcode")) {
            // 登陆凭证校验错误 code been used
            return R.error(500, "登陆失败");
        }


        // 校验通过
        Map<String, Object> ticket = JSONUtil.toBean(jsonResult, Map.class);

        // 判断当前用户是否存在
        User user = userService.checkIsExist((String) ticket.get("openid"));
        if (user == null) {
            user = new User();
            user.setOpenId(ticket.get("openid").toString());
            user.setAvatar(avatar);
            user.setName(nickname);
            // 保存到user表
//            userService.save(user);
            user = userService.saveUser(user);
        }
        ticket.put("user", user);
        return R.ok(ticket);
    }

}
